package com.wang.gallerybackend.manager;

import cn.hutool.core.io.FileUtil;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.GetObjectRequest;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.PicOperations;
import com.wang.gallerybackend.config.CosClientConfig;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 汪
 */
@Component
public class CosManager {
	@Resource
	private CosClientConfig cosClientConfig;
	@Resource
	private COSClient cosClient;

	// 将本地文件上传到 COS
	public PutObjectResult putObject(String key, File file)
			throws CosClientException {
		PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
		return cosClient.putObject(putObjectRequest);
	}

	// 下载文件
	public COSObject getObject(String key) {
		GetObjectRequest getObjectRequest = new GetObjectRequest(cosClientConfig.getBucket(), key);
		return cosClient.getObject(getObjectRequest);
	}

	// 将本地文件上传到 COS并解析图片
	public PutObjectResult putPictureObject(String key, File file)
			throws CosClientException {
		PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
		// 解析图片
		PicOperations picOperations = new PicOperations();
		picOperations.setIsPicInfo(1);
		//图片压缩(转成webp 格式)
		String webpKey = FileUtil.mainName(key) + ".webp";
		PicOperations.Rule compressRule = new PicOperations.Rule();
		compressRule.setFileId(webpKey);
		compressRule.setBucket(cosClientConfig.getBucket());
		compressRule.setRule("imageMogr2/format/webp");
		// 添加规则
		List<PicOperations.Rule> ruleList = new ArrayList<>();
		ruleList.add(compressRule);
		//仅对20kb以上的图片进行缩略图处理
		if (file.length() > 20 * 1024) {
			//缩略图处理
			PicOperations.Rule thumbnailRule = new PicOperations.Rule();
			String thumbnailKey = FileUtil.mainName(key) + "_thumbnail." + FileUtil.getSuffix(key);
			thumbnailRule.setFileId(thumbnailKey);
			thumbnailRule.setBucket(cosClientConfig.getBucket());
			thumbnailRule.setRule(String.format("imageMogr2/thumbnail/%sx%s>", 256, 256));
			ruleList.add(thumbnailRule);
		}
		picOperations.setRules(ruleList);
		putObjectRequest.setPicOperations(picOperations);
		return cosClient.putObject(putObjectRequest);
	}

	/**
	 * 删除文件
	 * @param key
	 */
	public void deleteObject(String key) {
		cosClient.deleteObject(cosClientConfig.getBucket(), key);
	}
}
